<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="380"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        @ok="onSubmit"
        @cancel="handleCancle"
    >
        <a-form class="dept-model" layout="horizontal" :model="formState" :rules="rules" ref="formRef">
            <a-form-item class="full-width" name="picTypeCode">
                <a-select v-model:value="formState.picTypeCode" :placeholder="t('yl.materialClassLabel')">
                    <a-select-option :value="item.picTypeCode" v-for="(item, index) in upList" :key="index">{{
                        item.picTypeCname
                    }}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item class="full-width" name="name">
                <a-input v-model:value="formState.name" :placeholder="t('yl.materialNameLabel')" />
            </a-form-item>
            <a-form-item class="full-width" name="picUrl">
                <a-upload
                    v-model:file-list="fileList"
                    :accept="picTypeCode == '1' ? 'video/mp4' : '.jpg, .jpeg, .png'"
                    name="avatar"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :before-upload="beforeUpload"
                    @change="handleChange"
                >
                    <img
                        v-if="formState.picUrl && picTypeCode !== '1'"
                        :src="formState.picUrl"
                        style="width: 100px"
                        alt="avatar"
                    />
                    <video
                        v-if="formState.picUrl && picTypeCode == '1'"
                        style="width: 100px"
                        :src="formState.picUrl"
                        controls="controls"
                    >
                        您的浏览器不支持 video 标签。
                    </video>

                    <div v-if="!formState.picUrl">
                        <loading-outlined v-if="loading"></loading-outlined>
                        <plus-outlined v-else></plus-outlined>
                        <div class="ant-upload-text">上传</div>
                    </div>
                </a-upload>
                <div style="position: absolute; top: 3px; color: #999">
                    {{ picTypeCode == '1' ? t('yl.materialNotesVide') : t('yl.materialNotes') }}
                </div>
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, watch } from 'vue';
import { addMaterial, postUpMaterial } from '@/api/material';

import { useI18n } from 'vue-i18n';
import _ from 'lodash';
interface FileItem {
    uid: string;
    name?: string;
    status?: string;
    response?: string;
    url?: string;
    type?: string;
    size: number;
    originFileObj: any;
}

// 表单校验规则
const initRules = (t: fn) => {
    return {
        picTypeCode: [{ required: true, message: t('yl.materialClassLabel'), trigger: 'blur' }],
        name: [{ required: true, message: t('yl.materialNameLabel'), trigger: 'blur' }],
        picUrl: [{ required: true, message: t('yl.materialImgLabel'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'roleModel',
    components: {},
    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },
        title: {
            type: String,
        },
        selectEditModel: {
            type: Array,
            default: () => [],
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        upList: {
            type: Array,
            default: () => [],
        },
        picTypeCode: {
            type: String,
            default: () => '0',
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        const { t } = useI18n();
        const showModal = computed(() => props.visible);
        let models = computed(() => props.selectEditModel as NormalObj[]);
        const formState = reactive({
            name: '',
            picUrl: '',

            picTypeCode: null,
            spec: {
                fileSize: '',
                heigh: 0,
                width: 0,
                extensionName: '',
            },
        });
        const fileList = ref<FileItem[]>([]);
        const picTypeCode = props.picTypeCode;
        console.log(props.upList);
        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                addMaterial(formState).then((res) => {
                    formRef.value.resetFields();
                    emit('submit', 'submit');
                });
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('submit', 'cancle');
        };
        const beforeUpload = (file: any) => {
            if (picTypeCode !== '1') {
                let filereader = new FileReader();
                filereader.onload = (e) => {
                    let src = e.target.result;
                    const image = new Image();
                    image.onload = function () {
                        console.log(image.width);
                        console.log(image.height);
                        if (image.width > 1280 && image.height > 800) {
                            console.log('Image must smaller than 800!');
                            file.status = false;
                            return false;
                        } else {
                            file.status = true;
                            return false;
                        }
                    };
                    image.src = src;
                };
                filereader.readAsDataURL(file);
            }
            let num = picTypeCode == '1' ? 20 : 3;
            const isLt3M = file.size / 1024 / 1024 < num;

            // 视频20
            if (!isLt3M) {
                file.status = false;
                console.log('Image must smaller than 2MB!');
            } else {
                file.status = true;
            }
            return false;
        };
        // 上传图片
        const handleChange = (info: any) => {
            console.log(picTypeCode);
            //获取最后一个.的位置
            let index = info.file.name.lastIndexOf('.');
            let ext = info.file.name.substr(index + 1);
            console.log(ext);
            let formData = new FormData();
            formData.append('file', info.file);
            postUpMaterial(formData).then((res) => {
                formState.picUrl = res.imgUrl;
                formState.spec.fileSize = res.fileSize;
                if (picTypeCode !== '1') {
                    formState.spec.width = res.width;
                    formState.spec.heigh = res.heigh;
                }

                formState.spec.extensionName = ext.toUpperCase();
            });
        };
        return {
            formRef,
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
            showModal,
            models,
            formState,
            fileList,
            t,
            rules,
            onSubmit,
            handleCancle,
            handleChange,
            beforeUpload,
            picTypeCode,
        };
    },
});
</script>
<style lang="scss" scoped>
.dept-model {
    @include flexWrap;
    width: 100%;
    .ant-form-item {
        @include flex;
        width: 50%;
        margin-right: 0;
        padding-right: $width10;
        margin-bottom: $width8;
        :deep .ant-form-item-label {
            flex-basis: $formLabel;
        }
        :deep .ant-form-item-control-wrapper {
            flex: 1;
        }
        :deep .ant-form-item-children,
        :deep .ant-input-number {
            width: 100%;
        }
        &.full-width {
            width: 100%;
        }
    }
}
</style>
